package com.zyd.blog.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Freemarker模板操作工具类
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @website https://www.zhyd.me
 * @date 2018/4/18 11:48
 * @since 1.0
 */
@Slf4j
@Component
public class FreeMarkerUtil {

    private static final String LT = "<";
    private static final String LT_CHAR = "&lt;";
    private static final String GT = ">";
    private static final String GT_CHAR = "&gt;";
    private static final String AMP = "&";
    private static final String AMP_CHAR = "&amp;";
    private static final String APOS = "'";
    private static final String APOS_CHAR = "&apos;";
    private static final String QUOT = "&quot;";
    private static final String QUOT_CHAR = "\"";
    private static final Logger logger = LoggerFactory.getLogger(FreeMarkerUtil.class);
    private static final String FREEMARKER_PREFIX = ".ftl";
    private final Path fileStorageLocation;
    private Configuration configuration;
    private String htmlPath;
    private String targetPrefix;

    @Autowired
    public FreeMarkerUtil(Configuration configuration, @Value("${spring.freemarker.static-html-path}") String htmlPath,
                          @Value("${spring.freemarker.target-prefix}") String targetPrefix) {
        this.targetPrefix = targetPrefix;
        this.htmlPath = htmlPath;
        this.configuration = configuration;
        this.fileStorageLocation = Paths.get(htmlPath).toAbsolutePath().normalize();
        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (Exception e) {
            logger.error("Cannot initialize file storage location...", e);
        }
    }

    /**
     * Template to String Method Note
     *
     * @param templateContent template content
     * @param map             tempate data map
     * @return
     */
    public static String template2String(String templateContent, Map<String, Object> map, boolean isNeedFilter) {
        if (StringUtils.isEmpty(templateContent)) {
            return null;
        }
        if (map == null) {
            map = new HashMap<>();
        }
        Map<String, Object> newMap = new HashMap<>(1);
        Set<String> keySet = map.keySet();
        if (keySet.size() > 0) {
            for (String key : keySet) {
                Object o = map.get(key);
                if (o != null) {
                    if (o instanceof String) {
                        String value = o.toString();
                        value = value.trim();
                        if (isNeedFilter) {
                            value = filterXmlString(value);
                        }
                        newMap.put(key, value);
                    } else {
                        newMap.put(key, o);
                    }
                }
            }
        }
        Template t = null;
        try {
            // 设定freemarker对数值的格式化
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
            cfg.setNumberFormat("#");
            t = new Template("", new StringReader(templateContent), cfg);
            StringWriter writer = new StringWriter();
            t.process(newMap, writer);
            return writer.toString();
        } catch (IOException e) {
            log.error("TemplateUtil -> template2String IOException.", e);
        } catch (TemplateException e) {
            log.error("TemplateUtil -> template2String TemplateException.", e);
        } finally {
            newMap.clear();
            newMap = null;
        }
        return null;
    }

    private static String filterXmlString(String str) {
        if (null == str) {
            return null;
        }
        str = str.replaceAll(LT, LT_CHAR);
        str = str.replaceAll(GT, GT_CHAR);
        str = str.replaceAll(AMP, AMP_CHAR);
        str = str.replaceAll(APOS, APOS_CHAR);
        str = str.replaceAll(QUOT, QUOT_CHAR);
        return str;
    }

    /**
     * 通过freemarker生成静态HTML页面
     *
     * @param templateName   模板名称
     * @param targetFileName 输出目录
     * @param map            模板数据
     * @throws Exception file、npe、io...
     */
    public void createHtml(String templateName, String targetFileName, Map<String, Object> map) throws Exception {
        //LOGGER.info("生成路径: {}, 模板路径：{}", htmlPath, ftlPath);
        //创建fm的配置
        //Configuration config = new Configuration(Configuration.VERSION_2_3_28);
        Configuration config = (Configuration) configuration.clone();
        //指定默认编码格式
        config.setDefaultEncoding("UTF-8");
        Template template = null;
        //设置模版文件的路径
        try {
            //config.setDirectoryForTemplateLoading(new File(ftlPath));
            //获得模版包
            template = config.getTemplate(templateName + FREEMARKER_PREFIX);
        } catch (Exception e) {
            logger.info("设置模板包异常：{}" + e.getMessage());
        }
        //判断是否使用自定义后缀名
        if (targetFileName.indexOf(".") > 0) {
            targetPrefix = "";
        }
        //Path targetLocation = fileStorageLocation.resolve(targetFileName + targetPrefix);
        File path = fileStorageLocation.toFile();
        if (!path.exists()) {
            path.mkdirs();
        }
        logger.info("Write File to: {},file name is: {}", fileStorageLocation.toFile().getPath(), targetFileName);
        //定义输出流，注意必须指定编码
        try (FileOutputStream fileInputStream = new FileOutputStream(new File(path.getPath() + "\\" + targetFileName));
             OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileInputStream, StandardCharsets.UTF_8);
             Writer writer = new BufferedWriter(outputStreamWriter)) {
            assert template != null;
            template.process(map, writer);
            logger.info("写入html");
        } catch (Exception e) {
            logger.error("生成异常: {}", e.getMessage());
        }
    }

}
